package com.ychen.core.server;

import com.ychen.core.config.ApplicationConfig;
import com.ychen.core.event.NotifyEvent;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * @author chenyuliao
 * @version 1.0
 * @description
 * @date 2020/12/13 11:54
 */
public class JettyServer {
    private static final int DEFAULT_PORT = 8180;
    private static final String CONTEXT_PATH = "/";
    private static final String MAPPING_URL = "/app/*";

    public static void run() {
        Server server = new Server(DEFAULT_PORT);

        Handler handler = new ServletContextHandler();
        server.setHandler(handler);
        server.setHandler(servletContextHandler(webApplicationContext()));
        try {
            server.start();
            server.join();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static ServletContextHandler servletContextHandler(WebApplicationContext context) {
        ServletContextHandler handler = new ServletContextHandler();
        handler.setContextPath(CONTEXT_PATH);
        handler.addServlet(new ServletHolder(new DispatcherServlet(context)), MAPPING_URL);
        handler.addEventListener(new ContextLoaderListener(context));
        return handler;
    }

    private static WebApplicationContext webApplicationContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(ApplicationConfig.class);
        return context;
    }

}
